package com.wef.demo.service.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Hibernate;

import com.gfa4j.hibernate.BaseObject;
import com.gfa4j.service.impl.BaseServiceImpl;
import com.wef.demo.entity.Clazz;
import com.wef.demo.entity.Student;
import com.wef.demo.entity.domain.ClazzDomain;
import com.wef.demo.entity.domain.StudentDomain;
import com.wef.demo.service.ClazzService;
import com.wef.demo.service.StudentService;

public class ClazzServiceImpl extends BaseServiceImpl implements ClazzService {

	private StudentService studentService;

	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	public Clazz loadClazzById(String clazzId) {
		return (Clazz) super.loadByPK(Clazz.class, ClazzDomain.clazzId, clazzId);
	}

	public Clazz addClazz(Clazz clazz) {
		clazz = (Clazz) super.saveObject(clazz);
		if (Hibernate.isPropertyInitialized(clazz, ClazzDomain.students) && clazz.getStudents() != null && clazz.getStudents().size() > 0) {
			for (Student student : clazz.getStudents()) {
				student.setRowStatus(BaseObject.ROWSTATUS_ADDED);
				student.setClazz(clazz);
			}
			studentService.saveOrUpdateStudents(clazz.getStudents());
		}
		return clazz;
	}

	public Clazz updateClazz(Clazz clazz) {

		if (Hibernate.isPropertyInitialized(clazz, ClazzDomain.students) && clazz.getStudents() != null && clazz.getStudents().size() > 0) {
			studentService.saveOrUpdateStudents(clazz.getStudents());
		}
		return (Clazz) super.updateObject(clazz);
	}

	public void removeClazz(Clazz clazz) {
		// 在lazyLoading为false的情况下重新载入子表数据
		List<Student> deleteStudents = super.findByProperty(Student.class, StudentDomain.clazz, clazz);
		// 执行子表的删除动作
		if (deleteStudents != null && deleteStudents.size() > 0) {// 判断
			for (Student aStudent : deleteStudents) {
				super.evict(aStudent.getClazz()); // 剔除被重复载入的主表对象
				studentService.removeStudent(aStudent);
			}
		}
		this.deleteObject(clazz);
	}

	public Clazz saveOrUpdateClazz(Clazz clazz) {
		if (clazz.getRowStatus() == BaseObject.ROWSTATUS_ADDED) {
			return this.addClazz(clazz);
		}
		if (clazz.getRowStatus() == BaseObject.ROWSTATUS_MODIFIED) {
			return this.updateClazz(clazz);
		}
		if (clazz.getRowStatus() == BaseObject.ROWSTATUS_DELETED) {
			this.removeClazz(clazz);
		}
		return clazz;
	}

	public Collection<Clazz> saveOrUpdateClazzs(Set<Clazz> entitys) {
		Set<Clazz> retClazzs = new HashSet<Clazz>();
		for (Clazz entity : entitys) {
			retClazzs.add(saveOrUpdateClazz(entity));
		}
		return retClazzs;
	}
}